document.getElementById('loginForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const username = this.username.value.trim();
    const password = this.password.value.trim();
    
    // 表单验证
    if (!username || !password) {
        alert('用户名和密码不能为空');
        return;
    }
    
    try {
        const data = new URLSearchParams();
        data.append('username', username);
        data.append('password', password);
        
        const res = await axios({
            method: 'post',
            url: '/users/login',
            data: data
        });
        
        if (res.data.code === 1) {
            // 保存token和用户信息
            localStorage.setItem('token', res.data.token);
            localStorage.setItem('userInfo', JSON.stringify(res.data.user));
            localStorage.setItem('nickname', res.data.user.username);
            
            // 登录成功后显示提示
            alert('登录成功！');
            // 确认后跳转到首页
            location.href = './index.html';
        } else {
            // 显示错误信息
            const errorMessage = document.getElementById('errorMessage');
            errorMessage.style.display = 'block';
        }
    } catch (err) {
        // 显示错误信息
        const errorMessage = document.getElementById('errorMessage');
        errorMessage.style.display = 'block';
        console.error('登录错误:', err);
    }
});

// 当用户开始输入时，隐藏错误信息
document.getElementById('username').addEventListener('input', () => {
    const errorMessage = document.getElementById('errorMessage');
    errorMessage.style.display = 'none';
});

document.getElementById('password').addEventListener('input', () => {
    const errorMessage = document.getElementById('errorMessage');
    errorMessage.style.display = 'none';
});

// 密码显示/隐藏功能
function togglePassword(inputId) {
    const input = document.getElementById(inputId);
    const button = input.nextElementSibling;
    const showPath = button.querySelector('.show-pwd');
    const hidePath = button.querySelector('.hide-pwd');
    
    if (input.type === 'password') {
        input.type = 'text';
        showPath.style.display = 'none';
        hidePath.style.display = 'block';
    } else {
        input.type = 'password';
        showPath.style.display = 'block';
        hidePath.style.display = 'none';
    }
} 